package cn.glccc.ds.exception;

import cn.glccc.common.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Datasource异常处理器
 *
 * @author glccc
 * @date 2024-06-19
 */
@Slf4j
@RestControllerAdvice
@Order(1)
public class DatasourceExceptionHandler {

    /**
     * MybatisSystem异常
     */
    @ExceptionHandler(MyBatisSystemException.class)
    public Result<?> handleMyBatisSystemException(MyBatisSystemException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();

        // 捕获数据库连接失败异常，此异常结构特殊，需要如此捕获
        Throwable rootCause = e.getCause();
        if (rootCause.getCause() instanceof CannotGetJdbcConnectionException) {
            log.error("请求地址'{}'，数据库连接失败：{}", requestURI, rootCause.getCause().getMessage());
            return Result.failure("数据库连接失败，请刷新重试！异常内容：" + rootCause.getCause().getMessage());
        }

        log.error("请求地址'{}'，发生MyBatisSystem异常：{}", requestURI, e.getMessage());
        return Result.failure("MyBatis系统异常，请联系管理员。" + e.getMessage());
    }

}
